/*********************************************************************************************************************
 * COPYRIGHT NOTICE
 * Copyright (c) 2018,逐飞科技
 * All rights reserved.
 * 技术讨论QQ群：	一群：179029047(已满)
 *					二群：244861897(已满)
 *					三群：824575535
 *
 * 以下所有内容版权均属逐飞科技所有，未经允许不得用于商业用途，
 * 欢迎各位使用并传播本程序，修改内容时必须保留逐飞科技的版权声明。
 *
 * @file			seekfree_vl53l0x.c
 * @company			成都逐飞科技有限公司
 * @author			逐飞科技(QQ3184284598)
 * @version			查看doc内version文件 版本说明
 * @Software		IAR 8.3 or MDK 5.24
 * @Taobao			https://seekfree.taobao.com/
 * @date			2020-03-25
 * @note			本文件作为IOT开发板seekfree_vl53l0x传感器API
 ********************************************************************************************************************/
#include "seekfree_vl53l0x.h"
#include "zf_utick.h"

#define ADDRESS_DEFAULT 0b0101001

uint8_t stop_variable[8]; // read by init and used when starting measurement; is StopVariable field of VL53L0X_DevData_t structure in API
uint32_t measurement_timing_budget_us[8];

//-------------------------------------------------------------------------------------------------------------------
//	@brief		初始化 VL53L0X
//	@param		Index	所选 FC 标识
//	@return		result			是否发送数据成功 true-完成 false-出错
//	Sample usage:				vl53l0x_init( FLEX_COMM0 );
//	@note		基于 VL53L0X_DataInit() & VL53L0X_StaticInit() & VL53L0X_PerformRefCalibration() 的顺序初始化传感器
//				这个函数不执行参考 SPAD 校准 VL53L0X_PerformRefSpadManagement() 除非传感器上加装了覆盖玻璃
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
bool vl53l0x_init (iot_flexcomm_index_list Index )
#else
bool vl53l0x_init ( flexcomm_index_list Index )
#endif
{
	uint8_t reg_data_buffer = 0x00;
	uint8_t i = 0;

	uint8_t spad_count;
	uint8_t ref_spad_map[6];
	uint8_t data_buffer[7];

	uint8_t first_spad_to_enable = 0;
	uint8_t spads_enabled = 0;

	bool spad_type_is_aperture;

	i2c_master_config_t iic_vl53l0x_config;												// 定义一个 Flex COMM 配置结构体
	zf_iic_master_get_default_config( &iic_vl53l0x_config);								// 获取默认设置
#ifdef IOT_BOARD
	iot_flexcomm_init(Index, FLEX_COMM_IIC_MASTER, &iic_vl53l0x_config);
#else
	zf_flexcomm_init((flexcomm_index_list)Index, FLEX_COMM_IIC_MASTER, &iic_vl53l0x_config);
#endif
	
	delay_ms( 500 );																										// 

	// VL53L0X_DataInit() begin
	// sensor uses 1V8 mode for I/O by default; switch to 2V8 mode if necessary
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV, &reg_data_buffer, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV, reg_data_buffer | 0x01 );	// 配置 IO 为 2.8V 模式

	// "Set I2C standard mode"
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x88, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 

	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x91, &stop_variable[Index], 1 );

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x00 );	// 

	// disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) limit checks
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_CONTROL, &reg_data_buffer, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_CONTROL, reg_data_buffer | 0x12 );	// 

	// set final range signal rate limit to 0.25 MCPS (million counts per second)
	vl53l0x_set_signal_rate_limit(Index, 0.25 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0xFF );	// 
	// VL53L0X_DataInit() end

	// VL53L0X_StaticInit() begin
	if (!vl53l0x_get_spad_info(Index, &spad_count, &spad_type_is_aperture ))
		return false;

	// The SPAD map (RefGoodSpadMap) is read by VL53L0X_get_info_from_device() in
	// the API, but the same data seems to be more easily readable from
	// GLOBAL_CONFIG_SPAD_ENABLES_REF_0 through _6, so read it from there
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_SPAD_ENABLES_REF_0, ref_spad_map, 6 );

	// -- VL53L0X_set_reference_spads() begin (assume NVM values are valid)
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4 );	// 

	first_spad_to_enable = spad_type_is_aperture ? 12 : 0; // 12 is the first aperture spad

	for ( i = 0; i < 48; i++ )
	{
		if (i < first_spad_to_enable || spads_enabled == spad_count)
		{
			// This bit is lower than the first one that should be enabled, or
			// (reference_spad_count) bits have already been enabled, so zero this bit
			ref_spad_map[i / 8] &= ~(1 << (i % 8));
		}
		else if ((ref_spad_map[i / 8] >> (i % 8)) & 0x1)
		{
			spads_enabled++;
		}
	}

	data_buffer[0] = GLOBAL_CONFIG_SPAD_ENABLES_REF_0;

	for( i = 1; i < 7; i++ )
	{
		data_buffer[1] = ref_spad_map[i-1];
	}

	zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, data_buffer, 7 );
	// -- VL53L0X_set_reference_spads() end

	// -- VL53L0X_load_tuning_settings() begin
	// DefaultTuningSettings from vl53l0x_tuning.h
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x09, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x10, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x11, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x24, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x25, 0xFF );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x75, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x4E, 0x2C );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x48, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x30, 0x20 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x30, 0x09 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x54, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x31, 0x04 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x32, 0x03 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x40, 0x83 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x46, 0x25 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x60, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x27, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x50, 0x06 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x51, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x52, 0x96 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x56, 0x08 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x57, 0x30 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x61, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x62, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x64, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x65, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x66, 0xA0 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x22, 0x32 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x47, 0x14 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x49, 0xFF );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x4A, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x7A, 0x0A );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x7B, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x78, 0x21 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x23, 0x34 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x42, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x44, 0xFF );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x45, 0x26 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x46, 0x05 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x40, 0x40 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x0E, 0x06 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x20, 0x1A );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x43, 0x40 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x34, 0x03 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x35, 0x44 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x31, 0x04 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x4B, 0x09 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x4C, 0x05 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x4D, 0x04 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x44, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x45, 0x20 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x47, 0x08 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x48, 0x28 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x67, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x70, 0x04 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x71, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x72, 0xFE );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x76, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x77, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x0D, 0x01 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x01, 0xF8 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x8E, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x00 );	// 
	// -- VL53L0X_load_tuning_settings() end

	// "Set interrupt config to new sample ready"
	// -- VL53L0X_SetGpioConfig() begin
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_INTERRUPT_CONFIG_GPIO, 0x04 );	// 
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GPIO_HV_MUX_ACTIVE_HIGH, &reg_data_buffer, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GPIO_HV_MUX_ACTIVE_HIGH, reg_data_buffer & ~0x10 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_INTERRUPT_CLEAR, 0x01 );	// 
	// -- VL53L0X_SetGpioConfig() end

	measurement_timing_budget_us[Index] = vl53l0x_get_measurement_timing_budget( Index );

	// "Disable MSRC and TCC by default"
	// MSRC = Minimum Signal Rate Check
	// TCC = Target CentreCheck
	// -- VL53L0X_SetSequenceStepEnable() begin

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0xE8 );	// 

	// -- VL53L0X_SetSequenceStepEnable() end

	// "Recalculate timing budget"
	vl53l0x_set_measurement_timing_budget(Index, measurement_timing_budget_us[Index] );

	// VL53L0X_StaticInit() end

	// VL53L0X_PerformRefCalibration() begin (VL53L0X_perform_ref_calibration())

	// -- VL53L0X_perform_vhv_calibration() begin

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0x01 );	// 
	if (!vl53l0x_perform_single_ref_calibration(Index, 0x40 ))
		return false;

	// -- VL53L0X_perform_vhv_calibration() end

	// -- VL53L0X_perform_phase_calibration() begin

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0x02 );	// 
	if (!vl53l0x_perform_single_ref_calibration(Index, 0x00 ))
		return false;

	// -- VL53L0X_perform_phase_calibration() end

	// "restore the previous Sequence Config"
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0xE8 );	//

	// VL53L0X_PerformRefCalibration() end

	delay_ms( 500 );	
	return true;
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		设置返回信号速率限制 该值单位为 MCPS (每秒百万次每秒)
//	@param		Index	所选 FC 标识
//	@return		limit_Mcps		设置的最小速率
//	Sample usage:				vl53l0x_set_signal_rate_limit( FLEX_COMM0, 0.25 );
//	@note		这个速率表示从目标反射并被设备检测到的信号的振幅
//				设置此限制可以确定传感器报告有效读数所需的最小测量值
//				设置一个较低的限制增加了传感器的测量范围
//				但似乎也增加了由于来自目标以外的物体的不需要的反射而得到不准确读数的可能性
//				默认为 0.25 MCPS 由 ST API 和这个库初始化。
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
void vl53l0x_set_signal_rate_limit (iot_flexcomm_index_list Index, float limit_Mcps )
#else
void vl53l0x_set_signal_rate_limit ( flexcomm_index_list Index, float limit_Mcps )
#endif
{
	uint8_t data_buffer[3];
	uint16_t limit_Mcps_16bit;
	assert (limit_Mcps >= 0 || limit_Mcps <= 511.99);
	limit_Mcps_16bit = (limit_Mcps * (1 << 7));

	data_buffer[0] = FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT;
	data_buffer[1] = (( limit_Mcps_16bit >> 8 ) & 0xFF );
	data_buffer[2] = ( limit_Mcps_16bit & 0xFF );

	zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, data_buffer, 3 );
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		获取信号速率限制 该值单位为 MCPS (每秒百万次每秒)
//	@param		Index	所选 FC 标识
//	Sample usage:				vl53l0x_get_signal_rate_limit( FLEX_COMM0 );
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
float vl53l0x_get_signal_rate_limit(iot_flexcomm_index_list Index )
#else
float vl53l0x_get_signal_rate_limit( flexcomm_index_list Index )
#endif
{
	uint8_t reg_data_buffer[2];
	uint16_t data_16bit;
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, reg_data_buffer, 2 );
	data_16bit = ((uint16_t)reg_data_buffer[0] << 8) | reg_data_buffer[1];
	return (float)data_16bit/(1 << 7);
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		设置测量定时预算(以微秒为单位)
//	@param		Index	所选 FC 标识
//	@return		budget_us		测量允许的时间
//	Sample usage:				vl53l0x_set_measurement_timing_budget( FLEX_COMM0, measurement_timing_budget_us );
//	@note		这是一次测量允许的时间 ST API 和这个库负责在测距序列的子步骤之间分配时间预算
//				更长的时间预算允许更精确的测量 增加一个N倍的预算可以减少一个sqrt(N)倍的范围测量标准偏差
//				默认为33毫秒 基于VL53L0X_set_measurement_timing_budget_micro_seconds()的最小值为20 ms
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
bool vl53l0x_set_measurement_timing_budget (iot_flexcomm_index_list Index , uint32_t budget_us )
#else
bool vl53l0x_set_measurement_timing_budget ( flexcomm_index_list Index , uint32_t budget_us )
#endif
{
	SequenceStepEnables enables;
	SequenceStepTimeouts timeouts;

	uint8_t data_buffer[3];
	uint16_t data;

	uint16_t const StartOverhead      = 1320; // note that this is different than the value in get_
	uint16_t const EndOverhead        = 960;
	uint16_t const MsrcOverhead       = 660;
	uint16_t const TccOverhead        = 590;
	uint16_t const DssOverhead        = 690;
	uint16_t const PreRangeOverhead   = 660;
	uint16_t const FinalRangeOverhead = 550;

	uint32_t const MinTimingBudget = 20000;

	if (budget_us < MinTimingBudget) { return false; }

	uint32_t used_budget_us = StartOverhead + EndOverhead;

	vl53l0x_get_sequence_step_enables(Index, &enables );
	vl53l0x_get_sequence_step_timeouts(Index, &enables, &timeouts);

	if (enables.tcc)
	{
		used_budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
	}

	if (enables.dss)
	{
		used_budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
	}
	else if (enables.msrc)
	{
		used_budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
	}

	if (enables.pre_range)
	{
		used_budget_us += (timeouts.pre_range_us + PreRangeOverhead);
	}

	if (enables.final_range)
	{
		used_budget_us += FinalRangeOverhead;

		// "Note that the final range timeout is determined by the timing
		// budget and the sum of all other timeouts within the sequence.
		// If there is no room for the final range timeout, then an error
		// will be set. Otherwise the remaining time will be applied to
		// the final range."

		if (used_budget_us > budget_us)
		{
			// "Requested timeout too big."
			return false;
		}

		uint32_t final_range_timeout_us = budget_us - used_budget_us;

		// set_sequence_step_timeout() begin
		// (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)

		// "For the final range timeout, the pre-range timeout
		//  must be added. To do this both final and pre-range
		//  timeouts must be expressed in macro periods MClks
		//  because they have different vcsel periods."

		uint16_t final_range_timeout_mclks =
		vl53l0x_timeout_microseconds_to_mclks(final_range_timeout_us,
				 timeouts.final_range_vcsel_period_pclks);

		if (enables.pre_range)
		{
			final_range_timeout_mclks += timeouts.pre_range_mclks;
		}

		data = vl53l0x_encode_timeout(final_range_timeout_mclks);

		data_buffer[0] = FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI;
		data_buffer[1] = (( data >> 8 ) & 0xFF );
		data_buffer[2] = ( data & 0xFF );

		zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, data_buffer, 3 );

		// set_sequence_step_timeout() end

		measurement_timing_budget_us[Index] = budget_us; // store for internal reuse
	}
	return true;
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		获取测量定时预算(以微秒为单位)
//	@param		Index	所选 FC 标识
//	Sample usage:				vl53l0x_get_measurement_timing_budget( FLEX_COMM0 );
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
uint32_t vl53l0x_get_measurement_timing_budget (iot_flexcomm_index_list Index )
#else
uint32_t vl53l0x_get_measurement_timing_budget ( flexcomm_index_list Index )
#endif
{
	SequenceStepEnables enables;
	SequenceStepTimeouts timeouts;

	uint16_t const StartOverhead     = 1910; // note that this is different than the value in set_
	uint16_t const EndOverhead        = 960;
	uint16_t const MsrcOverhead       = 660;
	uint16_t const TccOverhead        = 590;
	uint16_t const DssOverhead        = 690;
	uint16_t const PreRangeOverhead   = 660;
	uint16_t const FinalRangeOverhead = 550;

	// "Start and end overhead times always present"
	uint32_t budget_us = StartOverhead + EndOverhead;

	vl53l0x_get_sequence_step_enables(Index, &enables );
	vl53l0x_get_sequence_step_timeouts(Index, &enables, &timeouts);

	if (enables.tcc)
	{
		budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
	}

	if (enables.dss)
	{
		budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
	}
	else if (enables.msrc)
	{
		budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
	}

	if (enables.pre_range)
	{
		budget_us += (timeouts.pre_range_us + PreRangeOverhead);
	}

	if (enables.final_range)
	{
		budget_us += (timeouts.final_range_us + FinalRangeOverhead);
	}

	measurement_timing_budget_us[Index] = budget_us; // store for internal reuse
	return budget_us;
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		设置脉冲周期
//	@param		Index	所选 FC 标识
//	@param		type			预量程类型
//	@param		period_pclks	设定周期值 偶数有效 12-18 
//	Sample usage:				vl53l0x_set_vcsel_pulse_period( FLEX_COMM0, VcselPeriodPreRange, 12 );
//	@note		将给定周期类型(预量程或终量程)的VCSEL(垂直腔面发射激光)脉冲周期设置为PCLKs中的给定值
//				较长的周期增加传感器的测量范围	pre: 12到18(初始化默认值:14)	final: 8到14(初始化默认值:10)
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
bool vl53l0x_set_vcsel_pulse_period (iot_flexcomm_index_list Index, vcselPeriodType type, uint8_t period_pclks )
#else
bool vl53l0x_set_vcsel_pulse_period ( flexcomm_index_list Index, vcselPeriodType type, uint8_t period_pclks )
#endif
{
	uint8_t sequence_config;
	uint8_t reg_databuffer[3];
	uint16_t reg_buffer_16bit;

	uint8_t vcsel_period_reg = encodeVcselPeriod(period_pclks);

	SequenceStepEnables enables;
	SequenceStepTimeouts timeouts;

	vl53l0x_get_sequence_step_enables(Index, &enables );
	vl53l0x_get_sequence_step_timeouts(Index, &enables, &timeouts );

	// "Apply specific settings for the requested clock period"
	// "Re-calculate and apply timeouts, in macro periods"

	// "When the VCSEL period for the pre or final range is changed,
	// the corresponding timeout must be read from the device using
	// the current VCSEL period, then the new VCSEL period can be
	// applied. The timeout then must be written back to the device
	// using the new VCSEL period.
	//
	// For the MSRC timeout, the same applies - this timeout being
	// dependant on the pre-range vcsel period."


	if (type == VcselPeriodPreRange)
	{
		// "Set phase check limits"
		switch (period_pclks)
		{
			case 12:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x18 );	// 
				break;

			case 14:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x30 );	// 
				break;

			case 16:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x40 );	// 
				break;

			case 18:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x50 );	// 
				break;

			default:
				// invalid period
				return false;
		}
		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VALID_PHASE_LOW, 0x08 );	// 

		// apply new VCSEL period
		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VCSEL_PERIOD, vcsel_period_reg );	// 

		// update timeouts

		// set_sequence_step_timeout() begin
		// (SequenceStepId == VL53L0X_SEQUENCESTEP_PRE_RANGE)

		uint16_t new_pre_range_timeout_mclks =
		vl53l0x_timeout_microseconds_to_mclks(timeouts.pre_range_us, period_pclks);

		reg_buffer_16bit = vl53l0x_encode_timeout(new_pre_range_timeout_mclks);
		reg_databuffer[0] = PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI;
		reg_databuffer[1] = (reg_buffer_16bit >> 8)  & 0xFF;
		reg_databuffer[2] = reg_buffer_16bit & 0xFF;
		zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, reg_databuffer, 3 );

		// set_sequence_step_timeout() end

		// set_sequence_step_timeout() begin
		// (SequenceStepId == VL53L0X_SEQUENCESTEP_MSRC)

		uint16_t new_msrc_timeout_mclks =
		vl53l0x_timeout_microseconds_to_mclks(timeouts.msrc_dss_tcc_us, period_pclks);

		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_TIMEOUT_MACROP, (new_msrc_timeout_mclks > 256) ? 255 : (new_msrc_timeout_mclks - 1) );	// 

		// set_sequence_step_timeout() end
	}
	else if (type == VcselPeriodFinalRange)
	{
		switch (period_pclks)
		{
			case 8:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x10 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_LOW, 0x08 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_VCSEL_WIDTH, 0x02 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_CONFIG_TIMEOUT, 0x0C );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_LIM, 0x30 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
				break;

			case 10:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x28 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_LOW, 0x08 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_VCSEL_WIDTH, 0x03 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_CONFIG_TIMEOUT, 0x09 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_LIM, 0x20 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
				break;

			case 12:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x38 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_LOW, 0x08 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_VCSEL_WIDTH, 0x03 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_CONFIG_TIMEOUT, 0x08 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_LIM, 0x20 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
				break;

			case 14:
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x48 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VALID_PHASE_LOW, 0x08 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, GLOBAL_CONFIG_VCSEL_WIDTH, 0x03 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_CONFIG_TIMEOUT, 0x07 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, ALGO_PHASECAL_LIM, 0x20 );	// 
				zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
				break;

			default:
				// invalid period
				return false;
		}

		// apply new VCSEL period
		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VCSEL_PERIOD, vcsel_period_reg );	// 

		// update timeouts

		// set_sequence_step_timeout() begin
		// (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)

		// "For the final range timeout, the pre-range timeout
		//  must be added. To do this both final and pre-range
		//  timeouts must be expressed in macro periods MClks
		//  because they have different vcsel periods."

		uint16_t new_final_range_timeout_mclks =
		vl53l0x_timeout_microseconds_to_mclks(timeouts.final_range_us, period_pclks);

		if (enables.pre_range)
		{
			new_final_range_timeout_mclks += timeouts.pre_range_mclks;
		}

		reg_buffer_16bit = vl53l0x_encode_timeout(new_final_range_timeout_mclks);
		reg_databuffer[0] = FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI;
		reg_databuffer[1] = (reg_buffer_16bit >> 8)  & 0xFF;
		reg_databuffer[2] = reg_buffer_16bit & 0xFF;
		zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, reg_databuffer, 3 );

		// set_sequence_step_timeout end
	}
	else
	{
		// invalid type
		return false;
	}

	// "Finally, the timing budget must be re-applied"

	vl53l0x_set_measurement_timing_budget(Index, measurement_timing_budget_us[Index] );

	// "Perform the phase calibration. This is needed after changing on vcsel period."
	// VL53L0X_perform_phase_calibration() begin

	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, &sequence_config, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, 0x02 );	// 
	vl53l0x_perform_single_ref_calibration(Index, 0x0 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, sequence_config );	// 

	// VL53L0X_perform_phase_calibration() end

	return true;
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		获取脉冲周期
//	@param		Index	所选 FC 标识
//	@param		type			预量程类型
//	Sample usage:				vl53l0x_get_vcsel_pulse_period( FLEX_COMM0, VcselPeriodPreRange );
//	@note		在PCLKs中获取给定周期类型的VCSEL脉冲周期
//				基于VL53L0X_get_vcsel_pulse_period()
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
uint8_t vl53l0x_get_vcsel_pulse_period (iot_flexcomm_index_list Index, vcselPeriodType type )
#else
uint8_t vl53l0x_get_vcsel_pulse_period ( flexcomm_index_list Index, vcselPeriodType type )
#endif
{
	uint8_t data_buffer;
	if (type == VcselPeriodPreRange)
	{
		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_VCSEL_PERIOD, &data_buffer, 1 );
		return decodeVcselPeriod( data_buffer );
	}
	else if (type == VcselPeriodFinalRange)
	{
		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_VCSEL_PERIOD, &data_buffer, 1 );
		return decodeVcselPeriod( data_buffer );
	}
	else { return 255; }
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		开始连续测距测量
//	@param		Index	所选 FC 标识
//	@param		period_ms		测量间隔时间
//	Sample usage:				vl53l0x_start_continuous( FLEX_COMM0, 0 );
//	@note		如果period_ms(可选)为0或没有给定，则使用连续背靠背模式(传感器尽可能频繁地进行测量)
//				否则，使用连续计时模式，给定的测量间隔时间(以毫秒为单位)决定传感器进行测量的频率
//				基于VL53L0X_StartMeasurement ()
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
void vl53l0x_start_continuous (iot_flexcomm_index_list Index, uint32_t period_ms )
#else
void vl53l0x_start_continuous ( flexcomm_index_list Index, uint32_t period_ms )
#endif
{
	uint8_t reg_databuffer[5];
	uint16_t osc_calibrate_val;
	uint16_t reg_buffer_16bit;
	uint32_t reg_buffer_32bit;

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x91, stop_variable[Index] );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x00 );	// 

	if (period_ms != 0)
	{
		// continuous timed mode

		// VL53L0X_SetInterMeasurementPeriodMilliSeconds() begin

		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, OSC_CALIBRATE_VAL, reg_databuffer, 2 );
		osc_calibrate_val = ((uint16_t)reg_databuffer[0]<<8);
		osc_calibrate_val |= reg_databuffer[1];

		if (osc_calibrate_val != 0)
		{
			period_ms *= osc_calibrate_val;
		}

		reg_databuffer[0] = SYSTEM_INTERMEASUREMENT_PERIOD;
		reg_databuffer[1] = (period_ms >> 24) & 0xFF;
		reg_databuffer[2] = (period_ms >> 16) & 0xFF;
		reg_databuffer[3] = (period_ms >> 8) & 0xFF;
		reg_databuffer[4] = period_ms & 0xFF;
		zf_iic_master_send_data((flexcomm_index_list)Index, ADDRESS_DEFAULT, reg_databuffer, 5 );

		// VL53L0X_SetInterMeasurementPeriodMilliSeconds() end

		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x04 );	// 
	}
	else
	{
		// continuous back-to-back mode
		zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x02 );	// 
	}
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		停止连续测距测量
//	@param		Index	所选 FC 标识
//	Sample usage:				vl53l0x_stop_continuous( FLEX_COMM0 );
//	@note		基于 VL53L0X_StopMeasurement  ()
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
void vl53l0x_stop_continuous (iot_flexcomm_index_list Index )
#else
void vl53l0x_stop_continuous ( flexcomm_index_list Index )
#endif
{
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x01 );	// VL53L0X_REG_SYSRANGE_MODE_SINGLESHOT

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x91, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		当连续模式激活时 返回以毫米为单位的范围读数
//	@param		Index	所选 FC 标识
//	Sample usage:				vl53l0x_read_range_continuous_millimeters( FLEX_COMM0 );
//	@note		在开始单次射程测量后也调用此函数
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
uint16_t vl53l0x_read_range_continuous_millimeters (iot_flexcomm_index_list Index )
#else
uint16_t vl53l0x_read_range_continuous_millimeters ( flexcomm_index_list Index )
#endif
{
	uint8_t reg_databuffer[3];
	volatile uint16_t range;
//	startTimeout();
	while (( reg_databuffer[0] & 0x07 ) == 0)
	{
		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, RESULT_INTERRUPT_STATUS, reg_databuffer, 1 );
		if (range++ > 0xFFF)
		{
//			did_timeout = true;
			return 65535;
		}
	}

	// assumptions: Linearity Corrective Gain is 1000 (default);
	// fractional ranging is not enabled
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, RESULT_RANGE_STATUS + 10, reg_databuffer, 2 );
	range = ((uint16_t)reg_databuffer[0]<<8);
	range |= reg_databuffer[1];

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_INTERRUPT_CLEAR, 0x01 );

	return range;
}

//-------------------------------------------------------------------------------------------------------------------
//	@brief		执行单次射程测量
//	@param		Index	所选 FC 标识
//	Sample usage:				vl53l0x_read_range_single_millimeters( FLEX_COMM0 );
//	@note		在开始单次射程测量后也调用此函数
//-------------------------------------------------------------------------------------------------------------------
#ifdef IOT_BOARD
uint16_t vl53l0x_read_range_single_millimeters (iot_flexcomm_index_list Index )
#else
uint16_t vl53l0x_read_range_single_millimeters ( flexcomm_index_list Index )
#endif
{
	uint8_t reg_databuffer[3] = {0x01,0x01,0x01};
	volatile uint16_t range;
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x91, stop_variable[Index] );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x01 );	// 

	// "Wait until start bit has been cleared"
//	startTimeout();
	while (reg_databuffer[0] & 0x01)
	{
		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, reg_databuffer, 1 );
		if (range++ > 0x8FF0)
		{
//			did_timeout = true;
			return 65535;
		}
	}

	return vl53l0x_read_range_continuous_millimeters(Index);
}

#ifdef IOT_BOARD
bool vl53l0x_get_spad_info (iot_flexcomm_index_list Index, uint8_t * count, bool * type_is_aperture )
#else
bool vl53l0x_get_spad_info ( flexcomm_index_list Index, uint8_t * count, bool * type_is_aperture )
#endif
{
	uint8_t tmp;
	volatile uint16_t loop_count = 0;

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x00 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x06 );	// 
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, &tmp, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, tmp | 0x04 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x07 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x81, 0x01 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x01 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x94, 0x6b );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, 0x00 );	// 
//	startTimeout();
	tmp = 0x00;
	while( tmp == 0x00 )
	{
		zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, &tmp, 1 );
		loop_count++;
		if(loop_count == 0x8ff0)
			return false;
	}
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, 0x01 );	// 
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x92, &tmp, 1 );

	*count = tmp & 0x7f;
	*type_is_aperture = (tmp >> 7) & 0x01;

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x81, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x06 );	// 
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, &tmp, 1 );
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x83, tmp );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x01 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x00, 0x01 );	// 

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0xFF, 0x00 );	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, 0x80, 0x00 );	// 

	return true;
}

// Get sequence step enables
// based on VL53L0X_GetSequenceStepEnables()
#ifdef IOT_BOARD
void vl53l0x_get_sequence_step_enables(iot_flexcomm_index_list Index, SequenceStepEnables * enables )
#else
void vl53l0x_get_sequence_step_enables( flexcomm_index_list Index, SequenceStepEnables * enables )
#endif
{
	uint8_t sequence_config ;
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_SEQUENCE_CONFIG, &sequence_config, 1 );

	enables->tcc          = (sequence_config >> 4) & 0x1;
	enables->dss          = (sequence_config >> 3) & 0x1;
	enables->msrc         = (sequence_config >> 2) & 0x1;
	enables->pre_range    = (sequence_config >> 6) & 0x1;
	enables->final_range  = (sequence_config >> 7) & 0x1;
}

// Get sequence step timeouts
// based on get_sequence_step_timeout(),
// but gets all timeouts instead of just the requested one, and also stores
// intermediate values
#ifdef IOT_BOARD
void vl53l0x_get_sequence_step_timeouts(iot_flexcomm_index_list Index, SequenceStepEnables const * enables, SequenceStepTimeouts * timeouts )
#else
void vl53l0x_get_sequence_step_timeouts( flexcomm_index_list Index, SequenceStepEnables const * enables, SequenceStepTimeouts * timeouts )
#endif
{
	uint8_t reg_buffer[2];
	uint16_t reg16_buffer;

	timeouts->pre_range_vcsel_period_pclks = vl53l0x_get_vcsel_pulse_period(Index, VcselPeriodPreRange);

	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_TIMEOUT_MACROP, reg_buffer, 1 );
	timeouts->msrc_dss_tcc_mclks = reg_buffer[0] + 1;
	timeouts->msrc_dss_tcc_us = vl53l0x_timeout_mclks_to_microseconds( timeouts->msrc_dss_tcc_mclks, timeouts->pre_range_vcsel_period_pclks );

	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, reg_buffer, 2 );
	reg16_buffer = (( uint16_t ) reg_buffer[0] << 8 ) | reg_buffer[1];
	timeouts->pre_range_mclks = vl53l0x_decode_timeout( reg16_buffer );
	timeouts->pre_range_us = vl53l0x_timeout_mclks_to_microseconds( timeouts->pre_range_mclks, timeouts->pre_range_vcsel_period_pclks );

	timeouts->final_range_vcsel_period_pclks = vl53l0x_get_vcsel_pulse_period(Index, VcselPeriodFinalRange );

	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, reg_buffer, 2 );
	reg16_buffer = (( uint16_t ) reg_buffer[0] << 8 ) | reg_buffer[1];
	timeouts->final_range_mclks = vl53l0x_decode_timeout( reg16_buffer );

	if (enables->pre_range)
	{
		timeouts->final_range_mclks -= timeouts->pre_range_mclks;
	}

	timeouts->final_range_us = vl53l0x_timeout_mclks_to_microseconds( timeouts->final_range_mclks, timeouts->final_range_vcsel_period_pclks );
}

// based on VL53L0X_perform_single_ref_calibration()
#ifdef IOT_BOARD
bool vl53l0x_perform_single_ref_calibration (iot_flexcomm_index_list Index, uint8_t vhv_init_byte )
#else
bool vl53l0x_perform_single_ref_calibration ( flexcomm_index_list Index, uint8_t vhv_init_byte )
#endif
{
	uint8_t data_buffer;
	volatile uint16_t loop_count = 0;
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x01 | vhv_init_byte );	// 

//	startTimeout();
	zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_TIMEOUT_MACROP, &data_buffer, 1 );
	while ((data_buffer & 0x07) == 0)
	{
		if (loop_count > 0x8fe0) { return false; }
		if (loop_count++ % 0x10 == 0)
			zf_iic_read_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, MSRC_CONFIG_TIMEOUT_MACROP, &data_buffer, 1);
	}

	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSTEM_INTERRUPT_CLEAR, 0x01);	// 
	zf_iic_write_reg((flexcomm_index_list)Index, ADDRESS_DEFAULT, SYSRANGE_START, 0x00);	// 

	return true;
}

// Decode sequence step timeout in MCLKs from register value
// based on VL53L0X_decode_timeout()
// Note: the original function returned a uint32_t, but the return value is
// always stored in a uint16_t.
uint16_t vl53l0x_decode_timeout (uint16_t reg_val)
{
  // format: "(LSByte * 2^MSByte) + 1"
	return	(uint16_t)((reg_val & 0x00FF) <<
			(uint16_t)((reg_val & 0xFF00) >> 8)) + 1;
}

// Encode sequence step timeout register value from timeout in MCLKs
// based on VL53L0X_encode_timeout()
// Note: the original function took a uint16_t, but the argument passed to it
// is always a uint16_t.
uint16_t vl53l0x_encode_timeout (uint16_t timeout_mclks)
{
  // format: "(LSByte * 2^MSByte) + 1"

	uint32_t ls_byte = 0;
	uint16_t ms_byte = 0;

	if (timeout_mclks > 0)
	{
		ls_byte = timeout_mclks - 1;

		while ((ls_byte & 0xFFFFFF00) > 0)
		{
			ls_byte >>= 1;
			ms_byte++;
		}

		return (ms_byte << 8) | (ls_byte & 0xFF);
	}
	else { return 0; }
}

// Convert sequence step timeout from MCLKs to microseconds with given VCSEL period in PCLKs
// based on VL53L0X_calc_timeout_us()
uint32_t vl53l0x_timeout_mclks_to_microseconds (uint16_t timeout_period_mclks, uint8_t vcsel_period_pclks)
{
	uint32_t macro_period_ns = calcMacroPeriod(vcsel_period_pclks);

	return ((timeout_period_mclks * macro_period_ns) + (macro_period_ns / 2)) / 1000;
}

// Convert sequence step timeout from microseconds to MCLKs with given VCSEL period in PCLKs
// based on VL53L0X_calc_timeout_mclks()
uint32_t vl53l0x_timeout_microseconds_to_mclks(uint32_t timeout_period_us, uint8_t vcsel_period_pclks)
{
	uint32_t macro_period_ns = calcMacroPeriod(vcsel_period_pclks);

	return (((timeout_period_us * 1000) + (macro_period_ns / 2)) / macro_period_ns);
}

